package com.jeeplus.modules.common.excel.common.validator.impl.unique;

import com.jeeplus.modules.common.excel.common.anno.custorm.UniqueData;
import com.jeeplus.modules.common.excel.common.validator.abs.AbstractCustomValidator;
import org.apache.poi.ss.formula.functions.T;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wang.yishu
 * @version 1.0
 * @className UniqueData
 * @description 导入数据唯一性
 * @date 2022/7/13 15:52
 */
public class UniqueDataValidator extends AbstractCustomValidator {

    public final static String key = "importData";

    @Override
    public String customValidate(Object entity) {
        Class<?> entityClass = entity.getClass();
        UniqueData uniqueData = entityClass.getDeclaredAnnotation(UniqueData.class);
        Map<String, List<Object>> necessaryValidateData = this.chain.getNecessaryValidateData();
        List<Object> importData = necessaryValidateData.get(key);
        if (uniqueData != null) {
            List<Object> filterData = new ArrayList<>(importData);
            String[] fieldNames = uniqueData.uniqueFields();
            if (filterData.size() == 0) return null;
            for (String fieldName : fieldNames) {
                try {
                    Field declaredField = entityClass.getDeclaredField(fieldName);
                    declaredField.setAccessible(true);
                    Object value = declaredField.get(entity);
                    String valueStr = value == null ? "" : value.toString();
                    filterData = filterData.stream().filter(obj -> {
                        try {
                            Field field = obj.getClass().getDeclaredField(fieldName);
                            field.setAccessible(true);
                            Object targetValue = field.get(obj);
                            String targetValueStr = targetValue == null ? "" : targetValue.toString();
                            return targetValueStr.equals(valueStr);
                        } catch (NoSuchFieldException | IllegalAccessException e) {
                            return false;
                        }
                    }).collect(Collectors.toList());
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            if (filterData.size() > 1) {
                return uniqueData.msg();
            }
        }
        return "";
    }
}
